package com.xuanwei.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuanwei.core.cache.HomePageCache;
import com.xuanwei.core.enums.AdPositionType;
import com.xuanwei.core.exception.XwException;
import com.xuanwei.core.service.IXwAdManagerService;
import com.xuanwei.dao.entity.XwAdManager;
import com.xuanwei.dao.mapper.XwAdManagerMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2019-08-01
 */
@Service
public class XwAdManagerServiceImpl extends ServiceImpl<XwAdManagerMapper, XwAdManager> implements IXwAdManagerService {

    @Override
    public void addOrUpdate(Integer id, String image, String name, String url, Integer position, Integer orderBy, Integer showStatus) {
        if (id == null) {
            XwAdManager adManager = new XwAdManager();
            adManager.setImage(image);
            adManager.setUrl(url);
            adManager.setPosition(position);
            adManager.setOrderBy(orderBy);
            adManager.setShowStatus(showStatus);
            adManager.setName(name);
            adManager.setCreateTime(LocalDateTime.now());
            adManager.setUpdateTime(LocalDateTime.now());
            save(adManager);
        } else {
            XwAdManager adManager = getOne(new QueryWrapper<XwAdManager>().select("id").eq("id", id));
            if (adManager == null) {
                throw new XwException("数据不存在");
            }
            adManager.setImage(image);
            adManager.setName(name);
            adManager.setUrl(url);
            adManager.setPosition(position);
            adManager.setOrderBy(orderBy);
            adManager.setShowStatus(showStatus);
            updateById(adManager);
        }

    }

    @Override
    public void delete(Integer id) {
        getBaseMapper().deleteById(id);

    }

    @Override
    public void updateStatus(Integer id) {
        XwAdManager adManager = getOne(new QueryWrapper<XwAdManager>().select("id,show_status").eq("id", id));
        if (adManager == null) {
            throw new XwException("数据不存在");
        }
        adManager.setShowStatus(adManager.getShowStatus() == 0 ? 1 : 0);
        adManager.setUpdateTime(LocalDateTime.now());
        updateById(adManager);
    }

    @Override
    public void findPage(Integer position, Page<XwAdManager> page) {
        QueryWrapper<XwAdManager> wrapper = new QueryWrapper<>();
        if (position != null) {
            wrapper.eq("position", position);
        }
        page(page, wrapper);
        page.getRecords().forEach(s -> s.setPositionName(AdPositionType.getMsg(s.getPosition())));
    }
}
